package com.zw.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("进入zuul拦截-login拦截");
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取Request
        HttpServletRequest request = ctx.getRequest();
        //获取请求参数
        String token = request.getParameter("token");
        System.out.println("参数token=" + token);
//
//
        if (StringUtils.isBlank(token)) {
            //参数内容为空
            //拦截，拒绝路由
            ctx.setSendZuulResponse(false);
            //返回状态码
            ctx.setResponseStatusCode(401);
            //返回的响应体信息
            try {
                //不可以直接写中文，前端会显示中文乱码,加上这就解决中文乱码问题
                //以文本格式显示，字体比较大
                ctx.getResponse().setContentType("text/html;charset=UTF-8");
                //以json格式显示，字体比较小
//                ctx.getResponse().setContentType("application/json;charset=UTF-8");
//               上一句等同于  ctx.getResponse().setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                //
                ctx.getResponse().getWriter().write("token is 空的-------401");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
